package com.wanqing.login.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wanqing.login.common.lang.Result;
import com.wanqing.login.entity.User;
import com.wanqing.login.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    // 登录方法
    @RequestMapping("/login")
    public Result login(@RequestBody Map<String, String> map) {
        String name = map.get("username");
        log.info(name);
        String password = map.get("password");
        // 是否存在改用户名的用户
        User user = userService.getOne(new QueryWrapper<User>().eq("username", name));
        if (user == null) {
            return Result.fail("用户名不存在");
        }

        if(!user.getPassword().equals(password )){
            return Result.fail("密码错误");
        }

        return Result.succ(user);
    }

    // 注册方法
    @PostMapping("/save")
    public  Result save(@Validated @RequestBody User user){
        // 判断是否用户名已经存在
        User userTemp = userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if (userTemp != null) {
            return Result.fail("用户名已经存在");
        }
        if(user.getUsername() == null || user.getPassword() == null || user.getUsername().length()==0 || user.getPassword().length() == 0){
            return Result.fail("用户名和密码不能为空");
        }
        return userService.save(user) ? Result.succ(user) : Result.succ("新增失败");
    }
}
